package com.gxkj.drm.util;


import com.gxkj.drm.service.UserService;
import com.gxkj.spring.SpringBeanLocator;
import com.gxkj.drm.entitys.PushUser;


import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class LoginHelper {

    private static final String LOGIN_NAME = "boss_push_";

    //分隔符
    private static final String DELIM = "&";

    public static String getLoginName(final HttpServletRequest request) {
        String cookie = CookieUtil.getCookie(request, LOGIN_NAME);
        if (!StringUtils.isEmpty(cookie)) {
            cookie = Verify.decodeRC(cookie);
            String[] code = cookie.split(DELIM);
            if (code.length == 3) {
                String time = code[0];
                String name = code[1];
                String md5 = MD5.MD5_2(name + Verify.KEY + time).substring(4, 20);
                long loginTime = LoginHelper.toLong(time);
                // 判断时间,超过3天过期
                int days = LoginHelper.getDayInt(System.currentTimeMillis()) - LoginHelper.getDayInt(loginTime);
                if (days < 3 && md5.equals(code[2])) {
                    return name;
                }
            }
        }
        return null;

    }

    public static PushUser getLoginUser(final HttpServletRequest request) {
        String name = getLoginName(request);
        if (StringUtils.isEmpty(name))
            return null;
        PushUser user = SpringBeanLocator.getInstance().getBean(UserService.class).getUserByName(name);
        if (user != null) {
            user.setLoginIp(IpUtil.getIp(request));
        }

        return user;
    }

    public static void login(PushUser user, final HttpServletRequest request, final HttpServletResponse response) {
        long time = System.currentTimeMillis();
        String value = LoginHelper.join(DELIM, time, user.getName(), MD5.MD5_2(user.getName() + Verify.KEY + time)
                .substring(4, 20));
        value = Verify.encodeRC(value);
        CookieUtil.setSessionCookie(response, LOGIN_NAME, value, request.getServerName());
    }

    public static void logout(final HttpServletRequest request, final HttpServletResponse response) {
        CookieUtil.removeCookies(request, response, request.getServerName(), LOGIN_NAME);
    }

    private static long toLong(String str) {
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 得到从1970年1月1日到此日期的天数<br>
     * 可以利用返回值进行日期间隔的比较<br>
     * <br>
     * 适用于不需要构造Date对象的情况，如使用System.currentTimeMillis作为参数
     */
    public static int getDayInt(long time) {
        return (int) (time / TimeUnit.DAYS.toMillis(1));
    }

    public static String join(final String separator, Object... list) {
        StringBuilder sb = new StringBuilder(list[0].toString());
        for (int i = 1; i < list.length; i++) {
            sb.append(separator).append(list[i]);
        }
        return sb.toString();
    }
}
